package com.enlighten.aio.td;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.enlighten.aio.td.service.WxPayService;
import com.x.share.mid.utils.WxPayUtils;

import io.swagger.annotations.ApiOperation;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Henry
 * @since 2018-07-28
 */
@RestController
@RequestMapping("/td/wxpay")
public class WxpayController {
Logger logger = LoggerFactory.getLogger(WxpayController.class);	
	
	@Resource
	WxPayService wxPayService;
	
	@ApiOperation(value = "微信支付异步通知消息")
	@RequestMapping(value ="notify", method = { RequestMethod.POST })
	public void wxPayNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			Map<String, String> notify = WxPayUtils.stream2Map(request.getInputStream());
			logger.info(">>>> wx notify input map: {}", JSON.toJSONString(notify));
			boolean rlt = wxPayService.processNotify(notify);
			if (!rlt) {
				resultMap.put("return_code", "FAIL");
			} else {
				resultMap.put("return_code", "SUCCESS");
				resultMap.put("return_msg", "OK");
			}
		} catch (IOException e) {
			logger.warn("!!!! io exception: {}", e.getMessage());
			resultMap.put("return_code", "FAIL");
		}
		logger.info(">>>> wx notify output map: {}", JSON.toJSONString(resultMap));
		PrintWriter writer = response.getWriter();
		writer.write(WxPayUtils.map2xmlInRaw(resultMap));
		writer.flush();
		writer.close();
	}
	
	@ApiOperation(value = "微信支付异步通知消息")
	@RequestMapping(value ="/refund/notify", method = { RequestMethod.POST })
	public void proceeRefundNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			Map<String, String> notify = WxPayUtils.stream2Map(request.getInputStream());
			logger.info(">>>> wx notify input map: {}", JSON.toJSONString(notify));
			boolean rlt = wxPayService.proceeRefundNotify(notify);
			if (!rlt) {
				resultMap.put("return_code", "FAIL");
			} else {
				resultMap.put("return_code", "SUCCESS");
				resultMap.put("return_msg", "OK");
			}
		} catch (IOException e) {
			logger.warn("!!!! io exception: {}", e.getMessage());
			resultMap.put("return_code", "FAIL");
		}
		logger.info(">>>> wx notify output map: {}", JSON.toJSONString(resultMap));
		PrintWriter writer = response.getWriter();
		writer.write(WxPayUtils.map2xmlInRaw(resultMap));
		writer.flush();
		writer.close();
	}
}